<template>
	<div style="width:100%;height: 100%;background: #fff;">
		<div class="registrationForm">
			<x-header
				header-background-color="#fff"
				:left-options="{showBack: true,preventGoBack:true}"
				@on-click-back="GoBack"
			>
				
				{{flagDeBu?'登记出动情况':'补充出动信息'}}
				<!-- <a slot="right">Feedback</a> -->
			</x-header>
			<div class="registrationForm_content">
				<div class="registrationForm_content_form">
					<el-form 
					:model="ruleForm" 
					:rules="rules" 
					ref="ruleForm" 
					label-position="left" 
					label-width="90px" 
					hide-required-asterisk
					class="registrationForm_ruleForm outOf_form element_formCommons"
					>
						<el-form-item label="带队领导" prop="leadername">
							<el-input v-model="ruleForm.leadername" placeholder="请输入带队人员姓名"></el-input>
						</el-form-item>

						<x-switch title="负责人" v-model="remind" prevent-default @on-change="remindClick"></x-switch>

						<el-form-item label="职务" prop="protitle">
							<el-input v-model="ruleForm.protitle" @click.native="showPopupPicker=true" readonly placeholder="请选择职务"></el-input>
							<img @click="showPopupPicker=true" style="position: absolute;right: 7px;top: 10px;height: .32rem;width: .32rem;" src="../../assets/images/as_03.png" alt="">
						</el-form-item>
						<el-form-item label="联系电话" prop="conacttel">
							<el-input type="number" v-model="ruleForm.conacttel" placeholder="请输入联系电话"></el-input>
						</el-form-item>
						<el-form-item label="车辆台数" prop="carnum">
							<el-input type="number" v-model.number="ruleForm.carnum" placeholder="请输入车辆台数"></el-input>
						</el-form-item>
						<el-form-item label="出动人数" prop="numberOut">
							<el-input type="number" v-model.number="ruleForm.numberOut" placeholder="请输入出动人数">
								<template slot="append">人</template>
							</el-input>
						</el-form-item>
						<div class="carryingEquipment">
							<div v-for="(item,index) in ruleForm.carryingEquipment" :key="index">
								<el-form-item label="携带装备" 
								 :prop="'carryingEquipment.'+index+'.name'" :rules="rules.carryingEquipmentName">
									<!-- <el-input  v-model="item.name" placeholder="请携带装备" readonly>
									</el-input> -->
									<el-autocomplete
										class="inline-input"
										v-model="item.name"
										:fetch-suggestions="querySearch"
										placeholder="请选择装备"
										@select="handleSelect"
										></el-autocomplete>
									<!-- <img style="position: absolute;right: 7px;top: 10px;height: .32rem;width: .32rem;" src="../../assets/images/as_03.png" alt=""> -->
								</el-form-item>
								<el-form-item label-width="0px" label="" :prop="'carryingEquipment.'+index+'.num'" :rules="rules.carryingEquipmentNum">
										<el-input  type="number" v-model.number="item.num" placeholder="0">
										</el-input>
								</el-form-item>
								<div style="width: calc( 20% - 10px);float: left;display: flex;align-items: center;height: .64rem;">
									<img style="width: 45%;float: left;margin: 0 5%;" src="../../assets/images/jia.png" alt="" @click="addEquipment">
									<img style="width: 45%;float: left;" src="../../assets/images/jian.png" alt="" v-if="index>0" @click="reductionEquipment(index)">
								</div>

								<!-- <span class="jiajian" @click="addEquipment">+</span>
								<span class="jiajian" v-if="index>0" @click="reductionEquipment(index)">-</span> -->
							</div>
						</div>

						<el-form-item label="出行方式" prop="wayTravel">
							<el-input v-model="ruleForm.wayTravel" @click.native="popcxfs=true;" readonly placeholder="请选择出行方式"></el-input>
							<img @click="popcxfs=true;" style="position: absolute;right: 7px;top: 10px;height: .32rem;width: .32rem;" src="../../assets/images/as_03.png" alt="">
						</el-form-item>
						<el-form-item label="队伍地址" class="teamAddress">
							<!-- <el-input v-model="ruleForm.teamAddress" placeholder="队伍地址"></el-input> -->
							<div>
								{{ruleForm.teamAddress}}
							</div>
							<div @click="manualLocation">
								<img src="../../assets/images/icon/locationWhite.png" alt="">
								手动定位
							</div>
						</el-form-item>
						<el-form-item label="补充说明">
							<el-input v-model="ruleForm.added" placeholder="请输入说明" style="width: calc(100% - .8rem);"></el-input>
							<img @click="yySet" style="position: absolute;right: 0px;top: 1px;height: .65rem;width: .67rem;" src="../../assets/images/yuyin.png" alt="">
						</el-form-item>
						<el-form-item label="填写时间" prop="fillTime" class="fillTime">
							<!-- <el-input v-model="ruleForm.fillTime" placeholder="填写时间" readonly @click.native="visibility=true"></el-input> -->
							<el-input v-model="ruleForm.fillTime" placeholder="填写时间" readonly></el-input>
							<!-- <img src="../../assets/images/3_11.png" alt="" style="position: absolute;top:.17rem;left:10px;height: .3rem;width: .3rem;"> -->
						</el-form-item>
					</el-form>
				</div>
				<div v-if="!flagDeBu" class="submit" @click="submitForm('ruleForm')">保存</div>
				<div v-else class="dvTc">
					<div class="three" @click="submitForm('ruleForm')">进入救援模式</div>
					<span class="txt" @click="subPage">跳过</span>
				</div>
			</div>   
			<popup-picker :showCell="false"  :show.sync="showPopupPicker" ref="equip" :data="pation" @on-change="onChange" :columns="3" ></popup-picker>
			<popup-picker :showCell="false"  :show.sync="popcxfs" ref="cxfs" :data="options" @on-change="onChangecxfs" :columns="3" ></popup-picker>
    		<!-- <popup-picker :showCell="false"  :show.sync="showPopupPickerxd" ref="equipxd" :data="ment" @on-change="onChangexd" :columns="3"></popup-picker>  -->
			
        	<datetime style="display: none;" format="YYYY-MM-DD HH:mm"  v-model="ruleForm.fillTime" @on-change="change" :show.sync="visibility"></datetime>
		</div>
        <div @click="showPopupPicker=false;popcxfs=false;" v-if="showPopupPicker||popcxfs"  style="z-index: 500;width:100%;height: 100%;background: rgba(0,0,0,.5);position: fixed;left: 0;top: 0;">
		</div>
		<popup v-if="commonMapModel" v-model="commonMapModel" height="100%" width="100%" position="right">
			<commonMap ref="CMap" bigHeight="90vh" :Enable="true" initName="relocation" @handle="mapHandle" />
		</popup>
	</div>
</template>
 
<script>
import { XHeader, Previewer, PopupPicker, Datetime, Popup, XSwitch } from "vux";
import { getDataZW, getDataMaterial, saveData, getDataLeading } from "@/assets/js/service";
import { validatePhone } from '@/utils/validate'
import commonMap from "../commons/commonMap";

export default {
  props: ["refid","flagTrue"],
  components: {
    XHeader,
	Previewer,
	PopupPicker,
	Datetime,
	commonMap,
	Popup,
	XSwitch
  },
  data() {
    return {
		remind:true,
		leading:'',//0 没有 1有不是你， 2有是你

      	commonMapModel:false,//手动定位
		lontatStr:"",//保留android赋值的坐标
		  
		flagDeBu:false,//true为登记页面，false为补充页面
		ruleForm: {
			leadername: "", //带队人员姓名
			protitle:"",//职务
			protitleCode:"",//职务code
			conacttel:"",//联系电话
			carnum:"",//车辆台数
			numberOut:"",//出动人数
			wayTravel:"",//出行方式
			wayTravelCode:"",//出行方式code
			feedbacklon:"",//队伍地址(经度)
			feedbacklat:"",//队伍地址(纬度)
			teamAddress:"",//队伍地址
			added:"",//补充说明
			fillTime:"",//填写时间
			carryingEquipment:[
				{
					name:"",
					id:"",
					num:""
				}
			]
		},
		rules: {
			leadername: [
				{ required: true, message: "请输入带队人员姓名", trigger: ['change','blur'] },
				//   { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
			],
			protitle: [
				{ required: true, message: "请选择职务", trigger: ['change','blur'] },
			],
			conacttel: [
				{ required: true, message: "请输入联系电话", trigger: ['change','blur'] },
				{ validator:validatePhone, trigger:['change','blur']}
			],
			carnum: [
				{ required: true, message: "请输入车辆台数", trigger: ['change','blur'] },
      			{ type: 'number', message: '车辆台数必须为数字值'}
			],
			numberOut: [
				{ required: true, message: "请输入出动人数", trigger: ['change','blur'] },
      			{ type: 'number', message: '出动人数必须为数字值'}
			],
			wayTravel: [
				{ required: true, message: "请选择出行方式", trigger: ['change','blur'] },
			],
			// teamAddress: [
			// 	{ required: true, message: "队伍地址", trigger: "blur" },
			// ],
			fillTime: [
				{ required: true, message: "填写时间", trigger: ['change','blur'] },
			],
			carryingEquipmentName: [
				{ required: true, message: '请选择装备', trigger: ['change','blur'] },
				{ validator:this.carryingEquipmentValidate, trigger:['change','blur']}
			],
			carryingEquipmentNum: [
				{ required: true, message: '请选择个数', trigger: ['change','blur'] },
      			{ type: 'number', message: '个数必须为数字值'}
			]
		},
		//选择职务
		pation:[],
		showPopupPicker:false,
		//选择职务end

		// 出行方式
		popcxfs:false,
		options:[
			{
				value: '1',
				name: '摩托化推进',
				checked:"checked"
			}, {
				value: '2',
				name: '火车',
				checked:false
			}, {
				value: '3',
				name: '飞机',
				checked:false
			}
		],
		// 出行方式end

		visibility:false,//时间的打开
		
		// 携带装备
		// showPopupPickerxd:false,
		ment:'',
		// carryingEquipmentIndex:'',
		// 携带装备end
    };
  },
  created() {
	this.leadingAjax()
	if(this.$route.query.refid){
		this.flagDeBu=true;
	}else{
		this.flagDeBu=JSON.parse(this.flagTrue);
	}
	this.protitleAjax()//接口请求职务
	this.carryingEquipmentAjax()//接口请求携带装备
	// this.ruleForm.fillTime=this.$formatTimeStr(new Date())
	this.ruleForm.fillTime=this.$formatTimeStr(new Date()).split(":")[0]+':'+this.$formatTimeStr(new Date()).split(":")[1]
  },
  methods: {
	remindClick(value){
		let _this=this;
		console.log(value)
		if(value&&_this.leading==1){
			this.$vux.confirm.show({
				title: '提示',
				content: '当前已有负责人是否更换',
				onShow () {
					console.log('plugin show')
				},
				onHide () {
					console.log('plugin hide')
				},
				onCancel () {
					console.log('plugin cancel')
					_this.remind=false;
				},
				onConfirm () {
					console.log('plugin confirm')
				}
			})
		}
        
	},
	leadingAjax(){//查询当前队伍人员是否为队伍主导和出动情况的缓存回显
		let _this=this;
		let v ={
			"userid":_this.$store.state.user.userid,
			"orgcode":_this.$store.state.user.orgcode,
			"eventid":!_this.refid ? _this.$route.query.refid : _this.refid
		};
		getDataLeading(v,function(res){
			if(res.flag==1){//0 没有 1有不是你， 2有是你
				_this.remind = false;
				_this.leading = 1;
			}
			if(res.data!=""){
				_this.ruleForm.leadername=res.data.leadername; //带队人员姓名
				_this.ruleForm.protitle=res.data.posttypename; //职务
				_this.ruleForm.protitleCode=res.data.posttypecode;//职务code
				_this.ruleForm.conacttel=res.data.conacttel;//联系电话
				_this.ruleForm.carnum=res.data.carnum;//车辆台数
				_this.ruleForm.numberOut=res.data.dispatchnum;//出动人数
				_this.ruleForm.wayTravel=res.data.travelwayStr;//出行方式
				_this.ruleForm.wayTravelCode=res.data.travelway;//出行方式code
				_this.ruleForm.added=res.data.notes;//补充说明
				var equiplistStr=JSON.parse(res.data.equiplistStr)
				if(equiplistStr.length>0){
					_this.ruleForm.carryingEquipment=[];
					equiplistStr.forEach((item) => {
						_this.ruleForm.carryingEquipment.push({
							name:item.equipname,
							id:item.equipid,
							num:JSON.parse(item.equipnum)
						})
					});
				}
				// feedbacklon:"",//队伍地址(经度)
				// feedbacklat:"",//队伍地址(纬度)
				// teamAddress:"",//队伍地址
			}
		})
	},
	querySearch(queryString, cb) {
		var restaurants = this.ment;
		var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
		// 调用 callback 返回建议列表的数据
		cb(results);
	},
	createFilter(queryString) {
		return (restaurant) => {
			return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
		};
	},
	handleSelect(item) {//装备下拉菜单点击
		console.log(item);
	},
	carryingEquipmentValidate(rule, value, callback) {//判断装备在不在已有装备中
		var flag=false;
		for (let index = 0; index < this.ment.length; index++) {
			if(this.ment[index].value==value){
				flag=true;
			}
		}
		if (value == '' || value == undefined || value == null) {
			callback();
		} else {
			if (!flag && value != '') {
				callback(new Error('请输入准确的装备'));
			} else {
				callback();
			}
		}
	},  
    yySet() {//打开语音识别功能
		if (this.$isAndroid()) {
			window.android.openVoice();
		} else {
			console.log("打开语音识别功能");
		}
    },
    setContent(_text) {//安卓语音返回调用
		let _this = this;
		if (_text) {
			_this.ruleForm.added += _text;
		}
	},
    manualLocation(){//手动定位
		let _this=this;
		_this.commonMapModel=true;
		setTimeout(()=>{
			_this.$refs.CMap.locationSet(_this.lontatStr);
		},1000)
    },
    mapHandle(_obj){
		console.log(_obj)
		if(_obj.opentype&&_obj.opentype=='locationSure'){
			this.locationSet(_obj.locationStr);
		}
		this.commonMapModel=false;
    },
	refreshLocation(){//初始化定位
		if(this.$isAndroid()){
			console.log("invoking android!")
			window.android.getCurrentLocation();
		}else{
			this.locationSet("93.793409_31.896125_四川省雅安市拉亚镇桑木卡")
		}
	},
    locationSet(lontatStr){//地址
      	this.lontatStr=lontatStr;
		this.ruleForm.feedbacklon=lontatStr.split("_")[0];
		this.ruleForm.feedbacklat=lontatStr.split("_")[1];
		this.ruleForm.teamAddress=lontatStr.split("_")[2];   
    },
	carryingEquipmentAjax(){//接口请求携带装备
		let _this=this;
		let v ={
			"userid":_this.$store.state.user.userid
		};
		getDataMaterial(v,function(res){
          	console.log(res)
          	 _this.ment=[];
			res.data.forEach((item) =>{
				_this.ment.push({
					value : item.materialName,
					id:item.materialId,
				})
			})
        })
	},
	protitleAjax(){//接口请求职务
		let _this=this;
		let v ={
			"userid":_this.$store.state.user.userid
		};
		getDataZW(v,function(res){

			_this.pation = res.data
			_this.pation.forEach((item) =>{
				item.name = item.posttypename
				item.value = item.posttypecode
				item.ordernum = item.ordernum
			})
		})
	},
    onChange(v){//选择职务
		this.ruleForm.protitle =this.$refs.equip.getNameValues();
		this.ruleForm.protitleCode=v[0];
	},
    onChangecxfs(v){//选择出行方式
      	this.ruleForm.wayTravel =this.$refs.cxfs.getNameValues();
		this.ruleForm.wayTravelCode=v[0];
	},
    change(val){//填写时间
      	this.ruleForm.fillTime = val
      	console.log(val)
    },
	reductionEquipment(index){//减少
		this.ruleForm.carryingEquipment.splice(index,1);
	},
	addEquipment(){//增加
		this.ruleForm.carryingEquipment.push({
			name:"",
			id:"",
			num:""
		})
	},
	// carryingEquipmentClick(index){//携带装备的选择打开
	// 	this.carryingEquipmentIndex=index;
	// 	this.showPopupPickerxd=true;
	// },
	// onChangexd(v) {//携带装备选择赋值
	// 	let _this = this;
	// 	this.ruleForm.carryingEquipment[_this.carryingEquipmentIndex].name = _this.$refs.equipxd.getNameValues();
	// 	this.ruleForm.carryingEquipment[_this.carryingEquipmentIndex].id = v[0];
    // },
    GoBack() {
		this.$closeStates();
      	this.$emit("close");
	},
    submitForm(formName) {//校验
		this.$refs[formName].validate((valid,obj) => {
				console.log(this.ruleForm);
			if (valid) {
				console.log(this.ruleForm);
				this.submitSave();
			} else {
				this.$showBottomToast(obj[Object.keys(obj)[0]][0].message)
				console.log(obj[Object.keys(obj)[0]][0].message);
				return false;
			}
		});
	},
	submitSave() {//保存接口请求
		let _this = this;
		_this.$vux.loading.show({
			text: "Loading"
		});
		// 给装备添加上id
		_this.ruleForm.carryingEquipment.forEach((item, index) => {
			this.ment.forEach((item1,index1) => {
				if(item.name==item1.value){
					item.id=item1.id
				}
			});
		});
		// 给装备添加上id  end

		// 拼写携带装备格式
		let equip = [];
		_this.ruleForm.carryingEquipment.forEach((item, index) => {
			equip.push({
				equipid: item.id,
				equipnum: JSON.stringify(item.num),
				equipname:item.name
			});
		});
		equip = JSON.stringify(equip);
		// 拼写携带装备格式end
		let param = {
			userid: _this.$store.state.user.userid,
			orgcode: _this.$store.state.user.orgcode,
			eventid: !_this.refid ? _this.$route.query.refid : _this.refid,
			teamname: "",
			leadername: _this.ruleForm.leadername,
			protitle: _this.ruleForm.protitleCode,
			conacttel: _this.ruleForm.conacttel,
			dispatchnum: JSON.stringify(_this.ruleForm.numberOut),
			longitude: _this.ruleForm.feedbacklon,
			latitude: _this.ruleForm.feedbacklat,
			address: _this.ruleForm.teamAddress,
			filltime: _this.ruleForm.fillTime,
			districtcode: "",
			backstate: "",
			carnum: JSON.stringify(_this.ruleForm.carnum),
			travelway: _this.ruleForm.wayTravelCode,
			notes: _this.ruleForm.added,
			equiplistStr: equip,
			leading: _this.remind?'1':'0'
		};
		console.log(param)
		let paramObj = { obj: JSON.stringify(param) };
		saveData(paramObj, function(res) {
			if (res.status == "200") {
				_this.$vux.loading.hide();
				_this.$showBottomToast("保存成功");
				if(_this.flagDeBu){
					_this.$router.push({path:"/participateRescue"});
				}else{
					_this.GoBack();
				}
			} else {
				_this.$showBottomToast(res.message);
			}
			console.log(res);
		});
	},
	subPage(){//跳过
		this.$router.push({path:"/participateRescue"});
	},
  },
  mounted() {
	let _this=this;
	window.GoBack=this.GoBack;//安卓调用GoBack（手机back键返回问题）
	window.locationSet=this.locationSet;
	_this.refreshLocation();
    window.setContent=this.setContent;

  }
};
</script>
 
<style lang="less" scoped>
.registrationForm {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .registrationForm_content {
    width: 100%;
    height: calc(100% - 46px);
	overflow-y: auto;
	overflow-x: hidden;
	.registrationForm_content_form{
    	width: 100%;
		padding-left: .2rem;
	}
 	.submit{
		color: #fff;
		background: #139be5;
		padding: 15px 0;
		width: 100%;
		text-align: center;
		font-size: 16px
	}    
	.dvTc{
		text-align: center;
		.three{
			width: 60%;
			background-color: #1d9ed7;
			padding: 20px 0;
			border-radius: 5px;
			margin-left: 20%;
			margin: 20px 20%;
			text-align: center;
			color: #fff;
			font-size: .28rem;
		}
		span{
			padding: 20px;
		}
	}
	

  }
}
</style>
<style>
/* 特殊样式 */

/* 填写时间 */
.outOf_form .fillTime .el-input__inner{
	/* padding-left: calc(.3rem + 20px); */
	border: none;
}
/* 队伍地址 */
.outOf_form .teamAddress .el-form-item__content{
	display: flex;
    justify-content: center;
    align-items: center;
}
.outOf_form .teamAddress .el-form-item__content div:nth-child(1){
	float: left;
	width: calc(100% - 1.4rem - 10px);
	color: #333333;
	font-size: .24rem;
	line-height: 2;
}
.outOf_form .teamAddress .el-form-item__content div:nth-child(2){
	width: 1.4rem;
    height: .58rem;
    background-color: #409eff;
    border-radius: .06rem;
    display: flex;
    justify-content: center;
    align-items: center;
	float: right;
	font-size: .2rem;
	color: #fff;
}
.outOf_form .teamAddress .el-form-item__content div:nth-child(2) img{
	width: .17rem;
	height: .21rem;
	margin-right: 5px;
}
/* 携带装备 */
.outOf_form .carryingEquipment{
	overflow: hidden;
    margin-bottom: 0;
    padding: .2rem;
    padding-left: 0;
    border-bottom: 1px solid #c7c7c7;
}
.outOf_form .carryingEquipment .el-form-item:nth-child(1){
	border: none;
    padding: 0;
    width: 60%;
    float: left;
    margin-right: 10px;
}
.outOf_form .carryingEquipment .el-form-item:nth-child(2){
	border: none;
    padding: 0;
    width: 20%;
    float: left;
}
.outOf_form .carryingEquipment .jiajian{
	width: 22px;
    height: 22px;
    border: 2px solid #8b8b8b;
    float: left;
    text-align: center;
    font-size: 26px;
    color: #8b8b8b;
    line-height: 14px;
    border-radius: 50%;
    margin-top: 11px;
    margin-left: 5px;
}
/* 特殊样式 */

.outOf_form .vux-x-switch.weui-cell_switch{
	padding: .2rem;
    padding-left: 0;
	border-bottom: 1px solid #c7c7c7;
	overflow: hidden;
}
.outOf_form .vux-x-switch.weui-cell_switch>div:nth-child(1){
	width: 90px;
	font-size: .26rem;
    color: #333;
	float: left;
}
.outOf_form .vux-x-switch.weui-cell_switch>div:nth-child(2){
	float: left;
	width: calc(100% - 90px);
	text-align: left;
	    /* text-align: center; */
}
</style>
